/**
 * Created by liubin on 2014/11/24.
 * REST用基类
 */
define(['app'], function(app){

    "use strict";

    return app.factory('BaseService', function($resource, $log, NotificationService){
        function process (sev, funcName, args, posts, successFunc, failureFunc, errorFunc){
            var hasError = false;
            sev[funcName](args,
                posts,
                function (success) {
                    if (successFunc) {
                        // successFunc(success);
                        if(success.success){
                            successFunc(success);
                        }
                        else if(success.success === undefined){
                            successFunc(success);
                        }
                        else if(!success.success){
                            if(failureFunc){
                                failureFunc(success);
                            }
                            else{
                                NotificationService.warning("错误", success.messages.join('<br/>'));
                            }
                        }
                    }
                },
                function (error) {
                    $log.log('service failure');
                    hasError = true;
                    $log.log(error);
                    if (errorFunc) {
                        errorFunc(error);

                    }
                    else{
                        NotificationService.warning("错误", "服务器发生错误", null, 6000);
                    }
                }).$promise.catch(
                function (error) {
                    if (!hasError) {
                        $log.log('service $promise catch');
                        $log.log(error);
                        if (errorFunc) {
                            errorFunc(error);
                        }
                        else{
                            NotificationService.warning("错误", "处理错误", null, 6000);
                        }
                    }
                }
            );
        }
        return {
            process: function(sev, funcName, args, posts, successFunc, failureFunc, errorFunc){
                process(sev, funcName, args, posts, successFunc, failureFunc, errorFunc);
            }
        }
    });
});